<template>
  <view class="login-container">
    <view class="logo-box">
      <image class="logo-img" src="@/static/logo.png" mode="aspectFit" />
    </view>
    <view class="form-box">
      <view class="form-item">
        <text class="label">账号</text>
        <input class="input" v-model="loginForm.username" placeholder="手机号/用户名" type="text" />
      </view>
      <view class="form-item">
        <text class="label">密码</text>
        <uni-easyinput v-model="loginForm.password" type="password" placeholder="请输入密码" :clearable="false"
          :passwordIcon="true" class="password-input" />
      </view>
      <view class="form-item" v-if="captchaEnabled">
        <text class="label">验证码</text>
        <view class="code-row">
          <input class="input code-input" v-model="loginForm.code" placeholder="请输入验证码" type="text" />
          <image class="code-img" :src="codeUrl" @click="getCode" mode="aspectFit" />
        </view>
      </view>
      <view class="login-options">
        <view class="checkbox-item" @click="toggleRememberMe">
          <view class="checkbox" :class="{ checked: loginForm.rememberMe }"></view>
          <text class="checkbox-text">记住密码</text>
        </view>
      </view>
      <button class="login-btn" @click="handleLogin" :disabled="loading">
        <text v-if="!loading">登录</text>
        <text v-else>登录中...</text>
      </button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { login, getCodeImg } from '@/api/login';
import { setToken, setRememberData, getRememberData, removeRememberData } from '@/utils/auth';
import { validUsername, validPassword, validCode } from '@/utils/validate';

// 登录表单数据
const loginForm = ref({
  username: '',
  password: '',
  code: '',
  uuid: '',
  rememberMe: false,
});

// 验证码相关
const codeUrl = ref('');
const captchaEnabled = ref(true);
const loading = ref(false);

// 切换记住密码
const toggleRememberMe = (): void => {
  loginForm.value.rememberMe = !loginForm.value.rememberMe;

  // 如果取消记住密码，立即清除已保存的数据
  if (!loginForm.value.rememberMe) {
    removeRememberData();
  }
};

// 获取验证码
const getCode = async (): Promise<void> => {
  try {
    const res = await getCodeImg();
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled;
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.img;
      loginForm.value.uuid = res.uuid;
    }
  } catch (error) {
    uni.showToast({ title: '获取验证码失败', icon: 'none' });
  }
};

// 表单验证
const validateForm = (): boolean => {
  if (!validUsername(loginForm.value.username)) {
    uni.showToast({ title: '请输入账号', icon: 'none' });
    return false;
  }
  if (!validPassword(loginForm.value.password)) {
    uni.showToast({ title: '请输入密码', icon: 'none' });
    return false;
  }
  if (captchaEnabled.value && !validCode(loginForm.value.code)) {
    uni.showToast({ title: '请输入验证码', icon: 'none' });
    return false;
  }
  return true;
};

// 处理登录
const handleLogin = async (): Promise<void> => {
  if (!validateForm()) {
    return;
  }

  loading.value = true;
  try {
    const res = await login(
      loginForm.value.username.trim(),
      loginForm.value.password,
      loginForm.value.code,
      loginForm.value.uuid
    );


    if (res.code === 200) {
      setToken(res.token);

      // 处理记住密码
      if (loginForm.value.rememberMe) {
        // 保存记住密码数据
        setRememberData({
          username: loginForm.value.username.trim(),
          password: loginForm.value.password,
          rememberMe: true,
          timestamp: Date.now()
        });
      } else {
        // 清除记住密码数据
        removeRememberData();
      }

      uni.showToast({ title: '登录成功', icon: 'success' });

      // 跳转到首页
      setTimeout(() => {
        uni.reLaunch({
          url: '/pages/index/index'
        });
      }, 1500);
    } else {
      uni.showToast({ title: res.msg || '登录失败', icon: 'none' });
      // 重新获取验证码
      if (captchaEnabled.value) {
        getCode();
      }
    }
  } catch (error) {

    uni.showToast({ title: '登录失败，请重试', icon: 'none' });
    // 重新获取验证码
    if (captchaEnabled.value) {
      getCode();
    }
  } finally {
    loading.value = false;
  }
};

// 页面加载时获取验证码和填充记住的账号密码
onMounted(() => {
  // 获取验证码
  getCode();

  // 检查是否有记住的账号密码
  const rememberData = getRememberData();
  if (rememberData) {
    loginForm.value.username = rememberData.username;
    loginForm.value.password = rememberData.password;
    loginForm.value.rememberMe = rememberData.rememberMe;
  }
});
</script>

<style lang="scss" scoped>
.login-container {
  height: 100vh;
  background: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60rpx 40rpx;
  box-sizing: border-box;
  overflow: hidden;
}

.logo-box {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 60rpx;

  .logo-img {
    width: 120rpx;
    height: 120rpx;
    border-radius: 10rpx;
    background: #000;
  }
}

.form-box {
  width: 100%;
  max-width: 500rpx;
  display: flex;
  flex-direction: column;

  .form-item {
    margin-bottom: 40rpx;

    .label {
      font-size: 32rpx;
      color: #222;
      margin-bottom: 15rpx;
      display: block;
      font-weight: 500;
    }

    .input {
      width: 100%;
      border: none;
      border-bottom: 2rpx solid #e5e5e5;
      font-size: 28rpx;
      padding: 20rpx 0;
      color: #333;
      background: transparent;
      transition: border-color 0.3s;

      &:focus {
        border-bottom-color: #4095E5;
      }
    }

    .code-row {
      display: flex;
      align-items: center;
      gap: 20rpx;

      .code-input {
        flex: 1;
      }

      .code-img {
        width: 140rpx;
        height: 64rpx;
        border-radius: 8rpx;
        background: #f5f7fa;
        cursor: pointer;
      }
    }

    .password-input {
      border: none;
      border-bottom: 2rpx solid #e5e5e5;
      background: transparent;
      transition: border-color 0.3s;

      :deep(.uni-easyinput__content) {
        background-color: transparent;
        border: none;
      }

      :deep(.uni-easyinput__content-input) {
        padding: 20rpx 0;
        font-size: 28rpx;
        color: #333;
        border: none;
        background: transparent;

        &:focus {
          border-bottom-color: #4095E5;
        }
      }

      :deep(.uni-easyinput__content-input:focus) {
        border-bottom-color: #4095E5;
      }
    }
  }

  .login-options {
    display: flex;
    justify-content: space-between;
    margin: 20rpx 0 30rpx 0;

    .checkbox-item {
      display: flex;
      align-items: center;
      gap: 10rpx;

      .checkbox {
        width: 32rpx;
        height: 32rpx;
        border: 2rpx solid #ddd;
        border-radius: 4rpx;
        position: relative;
        transition: all 0.3s;

        &.checked {
          background: #4095E5;
          border-color: #4095E5;

          &::after {
            content: '';
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            width: 16rpx;
            height: 16rpx;
            background: #fff;
            border-radius: 2rpx;
          }
        }
      }

      .checkbox-text {
        font-size: 26rpx;
        color: #666;
      }
    }
  }

  .login-btn {
    background: #4095E5;
    color: #fff;
    border: none;
    border-radius: 50rpx;
    font-size: 32rpx;
    margin: 30rpx 0 20rpx 0;
    height: 88rpx;
    line-height: 88rpx;
    font-weight: 500;
    transition: background-color 0.3s;

    &:active:not(:disabled) {
      background: #0e375e;
    }

    &:disabled {
      background: #ccc;
      color: #999;
    }
  }
}
</style>
